import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';

/// author：william on 2021/4/9 11:43
/// email：362661044@qq.com

class AdvancedFilterSelectContent extends StatefulWidget {
  final double defaultHeight;
  final Widget child;
  final bool isExpanded;

  const AdvancedFilterSelectContent({Key key, this.defaultHeight = 32, @required this.child, this.isExpanded = false}) : super(key: key);

  @override
  _AdvancedFilterSelectContentState createState() => _AdvancedFilterSelectContentState();
}

class _AdvancedFilterSelectContentState extends State<AdvancedFilterSelectContent> {
  /// 最大高度
  double maxHeight;

  /// 最小高度
  double get minHeight => widget.defaultHeight;

  /// 当前高度
  double get _currentHeight => widget.isExpanded == true ? maxHeight : minHeight;

  @override
  Widget build(BuildContext context) {
    return ClipRRect(
      child: AnimatedContainer(
        height: _currentHeight,
        duration: Duration(milliseconds: 300),
        curve: Curves.ease,
        // 宽约束
        child: SingleChildScrollView(
          physics: NeverScrollableScrollPhysics(),
          child: _GetHeightBox(
            child: widget.child,
            onGetHeight: (height) => {maxHeight = height},
          ),
        ),
      ),
    );
  }
}

/// 直接使用 renderObjectWidget 获取真实高度
class _GetHeightBox extends SingleChildRenderObjectWidget {
  final Widget child;
  final Function(double) onGetHeight;

  _GetHeightBox({@required this.child, this.onGetHeight}) : super(child: child);

  @override
  RenderObject createRenderObject(BuildContext context) {
    return _RenderGetHeightBox(this.onGetHeight);
  }
}

class _RenderGetHeightBox extends RenderProxyBox {
  final Function(double) onGetHeight;

  _RenderGetHeightBox(this.onGetHeight);

  @override
  void performLayout() {
    if (child != null) {
      /// 通过宽约束 构建自己size 返回最大高度出去
      child?.layout(constraints, parentUsesSize: true);
      size = child.size;
      onGetHeight(size.height);
    } else {
      performResize();
    }
  }
}
